package com.hotkidceo.springcloud.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.hotkidceo.springcloud.util.DynamicDataSource;

@Configuration
public class DataSourceConfig {
	
	@Autowired
	private Environment env;
	
	@Bean(name = "bpmDS")
	//@ConfigurationProperties(prefix="jdbc")
	@Primary
	public DataSource dataSourceBPM(){		
		Properties props = new Properties();
        props.put("driverClass", env.getProperty("jdbc.driverClassName"));
        props.put("url", env.getProperty("jdbc.url"));
        props.put("username", env.getProperty("jdbc.username"));
        props.put("password", env.getProperty("jdbc.password"));
        try {
            return DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
		//return DataSourceBuilder.create().build();
	}
	
	@Bean(name = "goodsDS")
	//@ConfigurationProperties(prefix="jdbc2")
	public DataSource dataSourceGoods(){
		Properties props = new Properties();
        props.put("driverClass", env.getProperty("jdbc2.driverClassName"));
        props.put("url", env.getProperty("jdbc2.url"));
        props.put("username", env.getProperty("jdbc2.username"));
        props.put("password", env.getProperty("jdbc2.password"));
        try {
            return DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
		//return DataSourceBuilder.create().build();
	}
	
	/**
     * 动态数据源: 通过AOP在不同数据源之间动态切换
     * @return
     */
    @Bean(name = "dynamicDS")
    public DataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dataSourceBPM());

        // 配置多数据源
        Map<Object, Object> dsMap = new HashMap(5);
        dsMap.put("bmpDS", dataSourceBPM());
        dsMap.put("goodsDS", dataSourceGoods());

        dynamicDataSource.setTargetDataSources(dsMap);

        return dynamicDataSource;
    }
}
